# coding:utf-8
# @Time    : 2021/11/9 9:46
# @Author  : Martin
import os
import yaml
import pystache
import json
from datetime import datetime
from datetime import timedelta


def read_file(path):
    with open(path, encoding='utf-8') as f:
        return f.read()


def read_yaml(path):
    with open(path, 'rb') as f:
        res = yaml.load(f, Loader=yaml.FullLoader)
    return res


def get_test_data(file, level):
    work_path = os.path.dirname(os.path.dirname(__file__))
    with open(work_path + f'/case_data/{file}', 'rb') as f:
        res = yaml.load(f, Loader=yaml.FullLoader)
        # 对应优先级的用例列表
        case_list = res[level]
        # 所有用例名称列表
        cases_name = []
        # 所有用例步骤列表,包括执行步骤和预期结果
        cases_step = []

        for case in case_list:
            cases_name.append(case['name'])
            cases_step.append([case['steps'], case['expect']])

    return cases_name, cases_step


def get_test_datas(file, level):
    work_path = os.path.dirname(os.path.dirname(__file__))
    with open(work_path + f'/case_data/{file}', 'rb') as f:
        res = yaml.load(f, Loader=yaml.FullLoader)
        # 对应优先级的用例列表
        case_list = res[level]
        # # 所有用例名称列表
        # cases_name = []
        # # 所有用例步骤列表,包括执行步骤和预期结果
        # cases_step = []
        cases = {}

        for case in case_list:
            # cases_name.append(case['name'])
            # cases_step.append([case['steps'], case['expect']])
            case_id = case['id']
            case_name = case['name']
            case_steps = case['steps']
            case_expect = case['expect']
            cases[f'{case_id}'] = (case_name, case_steps, case_expect)

    return cases


def get_approve_data(act, auth, fun):
    """
    获取审批流节点信息
    :param act: 活动类型
    :param auth: 发起权限：1-head，2-area
    :param fun: 业务流程：create-新增 modify-修改
    :return: 审批流信息
    """
    work_path = os.path.dirname(os.path.dirname(__file__))
    with open(work_path + f'/conf/approve_info.yaml', 'rb') as f:
        res = yaml.load(f, Loader=yaml.FullLoader)

    return res[act][auth][fun]


def modify_data(txt, params: dict):
    json_text = json.dumps(txt)
    # print(f'json_text_bef={json_text}')
    # print(f'params={params}')
    json_text = pystache.render(json_text, params)
    # print(f'json_text_aft={json_text}')
    js = json.loads(json_text)
    # print(f'json_text_js={js}')
    return js


def merge_dict(*args):
    [args[0].update(args[i + 1]) for i in range(len(args) - 1)]
    return args[0]


def modify_floor_time(act_info, floor, offset=None):
    start_time = datetime.now()
    if offset:
        start_time = start_time + timedelta(minutes=offset)
    end_time = start_time + timedelta(minutes=5)
    start_time_str = start_time.strftime('%H:%M')
    end_time_str = end_time.strftime('%H:%M')
    return modify_data(act_info, {f'floor_start_time{floor}': start_time_str, f'floor_end_time{floor}': end_time_str})


def modify_act_time(act_info):
    start_time = datetime.now()
    end_time = start_time + timedelta(weeks=4)
    start_time_str = start_time.strftime('%Y-%m-%d %H:%M:%S')
    end_time_str = end_time.strftime('%Y-%m-%d %H:%M:%S')
    return modify_data(act_info, {'start_time': start_time_str, 'end_time': end_time_str})


def _generate_time_data(name, time_format, offset=None):
    """
    生成字典格式的参数
    :param name: 参数名称
    :param format: 时间格式
    :param offset: 偏移量
    :return:
    """
    _time = datetime.now()
    if offset:
        _time = _time + timedelta(minutes=offset)
    _time_str = _time.strftime(time_format)
    return {f'{name}': _time_str}


def generate_date_time(name, **kwargs):
    return _generate_time_data(name, time_format="%Y-%m-%d %H:%M:%S", **kwargs)


def generate_hour_time(name, **kwargs):
    return _generate_time_data(name, time_format="%H:%M", **kwargs)


if __name__ == '__main__':
    pass
    # print(read_file('../report/report.html'))
    # print(read_yaml('../k8s/selenium_k8s_deploy/selenium_grid_hub.yml'))
    # assert "test" in "tes1t1"
    # print(get_approve_data('offline_order_free_post', 'head', 'create'))
    # print(modify_act_time({'start_time': '{{start_time}}', 'end_time': '{{end_time}}'}))
    # txt = {'start_time': '33', 'end_time': '44'}
    txt = {"start_time": 33, "end_time": 44}
    print(type(txt))
    json_text = json.dumps(txt)
    print(type(json_text))
    print(json_text)
    assert json_text == "{'start_time': '33', 'end_time': '44'}",json_text
    # print(type(json_text))
    # print(json_text)
    # print(json.loads(json_text))
    # print(get_test_datas('online_order_gift.yaml', 'P1'))
    # cc = {'floor_start_time': '{{floor_start_time1}}', 'floor_end_time': '{{floor_end_time1}}',
    #       'start_time': '{{start_time}}', 'end_time': '{{end_time}}'}
    # cc = modify_floor_time(cc, 1, 5)
    # print(cc)
    # cc = modify_act_time(cc)
    # print(cc)
    # dict_str ='{"start_time":"11", "end_time":"22"}'

    # print(json.loads(dict_str))
    # print(type(json.loads(dict_str)))
    # print(eval(dict_str))
    # print(type(eval(dict_str)))

    # template = u'''
    #   {{greeting}}
    #    Property 1 is {{information.property1}}
    #    Property 2 is {{information.property2}}
    # '''
    #
    # context = {
    #     'greeting': 'Hello',
    #     'information': {
    #         'property1': 'bob',
    #         'property3': 42
    #     }
    # }
    #
    # print(pystache.render(template, context))
    # a = {'a': 1}
    # b = {'b': 2}
    # c = {'c': 2}
    # print(merge_dict(a, b, c))
